/*
    Contact info:
    bhepple@freeshell.org
    http://bhepple.freeshell.org

    Copyright (C) 1999-2008 Bob Hepple

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; see the file COPYING.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.

*/

#if defined(SM_TURBOC) || defined(__MSC__)

#include <stddef.h>
#include <sys/stat.h>
#include <string.h>

#include "ndir.h"

char *malloc();

DIR *opendir(path)
char 	*path;
{
	DIR		*dp;
	char		fullpath[80], c, s;
	struct stat	buf;

	strcpy(fullpath, path);
	if (*fullpath == 0)
		strcpy(fullpath, ".");

	/* Bless its pointed little head, MSDOS doesn't think root is a
	 * directory. Therefore ...
	 * Cope with root and drive designators:  . A: A:/ A:. A:./ and /
	 */
	if ((strlen(fullpath) == 1) && ((fullpath[0] == '/') || (fullpath[0] == '.')))
		;
	else if ((strlen(fullpath) == 2) && (fullpath[1] == ':'))
		;
	else if ((strlen(fullpath) == 3) && ((strcmp(&fullpath[1], ":/") == 0) ||
					     (strcmp(&fullpath[1], ":.") == 0)))
		;
	else if ((strlen(fullpath) == 4) && (strcmp(&fullpath[1], ":./") == 0))
		;
	else if (stat(fullpath, &buf) < 0)
		return(NULL);
	else if ((buf.st_mode | S_IFDIR) == 0)
		return(NULL);

	if ((dp = (DIR *) malloc(sizeof(DIR))) == NULL)
		return(NULL);

	/* Cope with path='A:' with current directory on A not = root */
	if ((strlen(fullpath) == 2) && (fullpath[1] == ':'))
		;
	else if (fullpath[strlen(fullpath) - 1] != '/')
		strcat(fullpath, "/");
	strcat(fullpath, "*.*");
	if (findfirst(fullpath, &(dp->d_ffblk), ALL_FILES) < 0) {
		free(dp);
		return(NULL);
	}
	dp->name_used = 0;
	return(dp);
}

struct direct *readdir(dirp)
DIR	*dirp;
{
	static struct direct	dp;

	if (dirp == NULL)
		return(NULL);
	if (!dirp->name_used)
		dirp->name_used = 1;
	else if (findnext(&(dirp->d_ffblk)) < 0)
		return(NULL);

	strcpy(dp.d_name, dirp->d_ffblk.FF_NAME);
	/* Add '.' to the name since MSDOS filenames are always considered to
	 * have an extension. Thus *.* matches all files, not just those with
	 * '.' in them.
	 */
	if (strchr(dp.d_name, '.') == NULL)
		strcat(dp.d_name, ".");
	strlwr(dp.d_name);
	dp.d_ino = 0;
	dp.d_reclen = 0;
	dp.d_namlen = strlen(dp.d_name);
	return(&dp);
}

int closedir(dirp)
DIR	*dirp;
{
	if (dirp != NULL)
		free(dirp);
	return(0);
}

#endif

/* For emacs:
 * Local Variables:
 * tab-width: 8
 * End:
 */
